<script lang="ts">
  import { createEventDispatcher } from 'svelte';
  export let value: string;
  const dispatch = createEventDispatcher();

  function handleChange(event: InputEvent): void {
    const newValue = (event.target as HTMLInputElement).value.replace(/[^\d.]/g, '');
    dispatch('change', newValue);
  }

  function preventInvalidKeys(event: KeyboardEvent): void {
    if ((event.which < 48 || event.which > 57) && event.which !== 8) {
      event.preventDefault();
    }
  }
</script>

<input type="text" value={value.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1 ')} on:input={handleChange} on:change={handleChange} on:keydown={preventInvalidKeys} />
